<?php
/**
 * @title 56. 合并区间 - 遍历
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[][] $intervals
     * @return Integer[][]
     */
    function merge($intervals) {
        /**
         * @since 2020-07-23 遍历
         */
        for ($i=0, $len=count($intervals); $i<$len-1; $i++){
            list($left1, $right1) = $intervals[$i];

            /**
             * @since 2020-07-23 剩下的区间找, 能否合并
             */
            for($j=$i+1; $j<$len; $j++){
                list($left2, $right2) = $intervals[$j];

                /**
                 * @since 2020-07-23 交叉, 包含
                 */
                if($left2>=$left1){
                    if($left2<=$right1){
                        unset($intervals[$i]);
                        $intervals[$j] = [$left1, max($right1, $right2)];
                        break;
                    } else {}
                } elseif($left1<=$right2) {
                    unset($intervals[$i]);
                    $intervals[$j] = [$left2, max($right1, $right2)];
                    break;
                } else {}

                // if($left2>=$left1 AND $left2<=$right1){
                //     unset($intervals[$i]);
                //     $intervals[$j] = [$left1, max($right1, $right2)];
                //     break;
                // } else {}
                // if($left1>=$left2 AND $left1<=$right2){
                //     unset($intervals[$i]);
                //     $intervals[$j] = [$left2, max($right1, $right2)];
                //     break;
                // } else {}
            }
        }

        /**
         * @return
         */
        return $intervals;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.23_6.php
 */
$datas = [
    [[1,3],[2,6],[8,10],[15,18]],
    [[1,4],[4,5]],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->merge($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
